<?PHP
  class FileServer{

    public static $uploadFailure = "";

    /**
     *
     * @param string $dir
     * @return array
     */
    public static function getFiles($dir){
      $res = array();
      $oDir = openDir($dir);
      
      while($item = readDir($oDir)){
        if(is_file($dir."/".$item)){
          $res[] = $item;
        }
      }

      closeDir($oDir);
      
      return $res;
    }

    /**
     *
     * @param string $dir
     * @return array
     */
    public static function getFolders($dir){
      $res = array();
      $oDir = openDir($dir);
      
      while($item = readDir($oDir)){
        if(is_dir($dir."/".$item)){
          if($item != "." && $item != ".."){
            $res[] = $item;
          }
        }
      }

      closeDir($oDir);
      
      return $res;
    }

    /**
     *
     * @param string $base
     * @param string $name
     * @return mixed 
     */
    public static function createFolder($base,$name){
      $res = false;
      if(!file_exists($base."/".$name)){
        $res = mkdir($base."/".$name,0777);
      }
      $args['name'] = $base."/".$name;
      if(isset($res) && $res) EventManager::RaiseEvent("folder_created",$args);
      return $res;
    }
    
    /**
     * 
     */
    public static function IsValidFoldername($name){
        $matches = null;
        preg_match("/^[A-Za-z0-9_\-]*$/", $name,$matches);
        return isset($matches) && sizeof($matches) > 0;
    }
    
    /**
     *
     * @param string $base
     * @param string $file
     * @return boolean 
     */
    public static function upload($base,$file){
      $res = false;
      if(self::checkUploadFile($file)){
        $tempname = $file['tmp_name'];
        $name = $file['name'];
        $res = copy($tempname, $base."/".$name);
        $args['name'] = $base."/".$name;
        if($res) EventManager::raiseEvent("file_uploaded",$args);
      }
      return $res;
    }

    /**
     *
     * @param string $file
     * @return boolean 
     */
    protected static function checkUploadFile($file){
      $res = true;
      self::$uploadFailure = "";

      switch($file['error']){
        case 0:
          break;
        case 1:
          $res = false;
          self::$uploadFailure = str_replace("{VAR:MAX_FILESIZE}",ini_get('upload_max_filesize'),Language::DirectTranslate("UPlOAD_FAILED_SIZE"));
          break;
        case 2:
          $res = false;
          self::$uploadFailure = str_replace("{VAR:MAX_FILESIZE}",IMAGE_MAX_IMAGE_SIZE,Language::DirectTranslate("UPlOAD_FAILED_IMAGE_SIZE"));
          break;
        case 3:
          $res = false;
          self::$uploadFailure = Language::DirectTranslate("UPlOAD_FAILED_PARTIALLY");
        case 4:
          $res = false;
          self::$uploadFailure = Language::DirectTranslate("UPlOAD_FAILED_NONE");
      }

      return $res;
    }

  }

?>